from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from questionnaire.views_statistics import *
from questionnaire.models import Question, Submit, Questionnaire


@api_view(['POST', ])
def getVoteData(request):
    qid = request.data.get('qid')
    ls_submitted = list(Submit.objects.filter(wjId=qid).filter(is_submitted=True).values_list('id', flat=True))
    questions = Question.objects.filter(wjId=qid)
    questionnaire = Questionnaire.objects.get(id=qid)
    if questionnaire.type == "vote":
        dict_state = []
        for q in questions:
            # 本题填写率
            dict_q = {'id': q.id, 'title': q.title, 'type': q.type,
                    'filling_rate': str(getFillingRate(q, ls_submitted) * 100) + '%'}
            # 针对不同题型进行不同分析
            if q.type in ['single', 'multi']:
                dict_q['result'] = getResult(q, ls_submitted)
                dict_q['option_count'] = optionCount(q.id, ls_submitted)
            dict_state.append(dict_q)
        response = {'code': 0, 'msg': 'success', 'statistics': dict_state}
        return Response(response, status=status.HTTP_200_OK)
    else:
        return Response({'code': 0, 'msg': 'success', 'statistics': null}, status=status.HTTP_200_OK)
